import 'dart:math';

import 'package:flutter/material.dart';
import 'dart:io';
import 'package:flutter_uxin/base/baseTab.dart';
import 'package:flutter_uxin/Login/areaSelect.dart';
import 'package:flutter_uxin/Login/Parsers/areaDNS.dart';

import 'package:flutter_des/flutter_des.dart';
import 'package:flutter_uxin/Tools/Define/Define.dart';

import 'package:flutter_uxin/Compontents/http_Dio/http_manager.dart';
import 'package:flutter_uxin/Compontents/http_Dio/result_data.dart';
import 'package:flutter_uxin/Compontents/http_Dio/address.dart';

import 'package:flutter_uxin/Login/Parsers/users_profile.dart';

import 'dart:convert';

import 'package:dio/dio.dart';

import 'package:flutter_picker/flutter_picker.dart';
import 'package:flutter_uxin/Tools/Define/Device.dart';
import 'package:flutter_uxin/Tools/config/RSATool.dart';

import 'package:flutter_uxin/Tools/config/md5Tool.dart';
import 'package:flutter_uxin/Login/Parsers/LoginProfile.dart';

import 'package:shared_preferences/shared_preferences.dart';
//import 'package:flutter/cupertino.dart';//cupertino风格的弹出


class LoginRootPage extends StatefulWidget {
  LoginRootPage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _LoginRootPageState createState() => _LoginRootPageState();
}

class _LoginRootPageState extends State<LoginRootPage> {
  bool _isObscure = false;

  areaDNS area;

  final _passwordController = TextEditingController();
  final _accountController = TextEditingController();


  getAreaDNS() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String areaDNS_Str = prefs.getString('areaDNS');

    if((areaDNS_Str is String) && (areaDNS_Str.isNotEmpty == true)){
      Map  areaDNSMap = jsonDecode(areaDNS_Str);
      areaDNS  area_cache = new    areaDNS.fromJson(areaDNSMap);

      setState(() {
        area = area_cache;
      });

    }




  }


  showAlart(String content,{String title}){

    print('content--------$content');
    showDialog(
        context: context,
        barrierDismissible: false,//// user must tap button!
        builder: (context) {
          return  new AlertDialog(
            title: new Text(title),
            content: new SingleChildScrollView(
              child: new ListBody(
                children: <Widget>[
                  new Text(content),
                ],
              ),
            ),
            actions: <Widget>[
              new FlatButton(
                child: new Text('确定'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        }
    );
  }


  checkResult() {
    String  _account =  _accountController.text;
    String  _password =  _passwordController.text;
    if(_account.isEmpty == true){
      showAlart('账号不能为空',title: '错误');
    }else   if(_password.isEmpty == true){
      showAlart('密码不能为空',title: '错误');
    }else   if(area == null){
      showAlart('请选择登录区域',title: '错误');
    }else{
      getRelation();
    }




  }




  getRelation() async{

    String  _account =  _accountController.text;
    var encrypt = await FlutterDes.encryptToHex(_account, youjiaotongKey, iv:giv);
    _account =   encrypt.toLowerCase();
    String device_type = Device.getDevice_type();



    var relationAccount_url = await Address.url_get_RelationAccount;
    ResultData res = await HttpManager.getInstance().post(relationAccount_url,{"mobile":"$_account","device_type":"$device_type"},responseType:ResponseType.plain);
//    print('res.data-----url_get_RelationAccount-----------------${res.data}');
    if(res.isSuccess){
      setState(() {
        String str = res.data;
//        print('url_get_RelationAccount--------responseJson--------------$str');
        Map  responseJson = jsonDecode(str);
        users_list  users = new users_list.fromJson(responseJson);
        _showDialog(users.usersProfile);
//        print('name----------------------${users.usersProfile.first.name}');
      });
    }else{

    }

  }

  List <PickerItem> addPickerDataList(List <UsersProfile>  users_list){
    List <PickerItem> pickerDataList = new List();

    users_list.forEach(
            (usersProfile){

              String typeName = '';
              if(usersProfile.userType == 1){
                typeName = '学生';
              }else if(usersProfile.userType == 2){
                typeName = '家长';
              }else if(usersProfile.userType == 3){
                typeName = '老师';
              }
              String content = '${usersProfile.realName}  ($typeName)';
              var  item =   new PickerItem(text:Text('$content') ,value:usersProfile);
              pickerDataList.add(item);
        }
    );
      return pickerDataList;
  }

  void _showDialog(List <UsersProfile>  users_list){

    List pickerDataList = addPickerDataList(users_list);
//    print('pickerDataList---------------${pickerDataList}');
    new Picker(
        adapter: PickerDataAdapter(data:pickerDataList ),
        changeToFirst: true,
        hideHeader: false,
        onConfirm: (Picker picker, List value) {
          UsersProfile usersProfile =  picker.adapter.getSelectedValues().first;
          String  _password =  _passwordController.text;
          tryLogin(usersProfile.name,_password);
//          print('getSelectedValues-----------${usersProfile.name}');
//          print(picker.adapter.text);
        },

    ).showModal(this.context); //_scaffoldKey.currentState);
//  print('usersProfile---------------${usersProfile}');

  }

  void tryLogin(String name ,String passWord) async{
    String device_type = Device.getDevice_type();
    String deviceID = await Device.deviceID();
//    String  pwdRsa = await  RSATool.encode(passWord);
//

    String  pwdRsa = '53B46F467E30942B9958CA55CD531E514F7229958CDEA91E1F1595528FB5A0231193E85EE0D7F3A3D14913D554FA7D295A65C63B089106E6F40409CE71A15F11FA57AA74DDE781929EFB6E2747BCE81C20D289344870DEA91ADA93ECF5D39FF9ECE728514AF4AA59EDA89F766806440B425500FD147B19DF75E1A0510D018A62';

    String passWord_md5 =   md5Tool.generateMd5(passWord);

    var encrypt = await FlutterDes.encryptToHex(name, youjiaotongKey, iv:giv);

    String name_des =  encrypt.toLowerCase();

    var relationAccount_url = await Address.url_get_LoginForUxin;
    ResultData res = await HttpManager.getInstance().post(relationAccount_url,{'user_name':'$name_des','user_password':'$passWord_md5','device_type':'$device_type','device_identifier':'$deviceID','encodeP':'4','mobile':'','pwdRsa':'$pwdRsa','key':'','token':'',},responseType:ResponseType.plain);
//    print('res.data-----url_get_RelationAccount-----------------${res.data}');
    if(res.isSuccess){
      setState(() {
        String str = res.data;
//        print('url_get_RelationAccount--------responseJson--------------$str');
        Map  responseJson = jsonDecode(str);
        LoginProfile  user = new LoginProfile.fromJson(responseJson);

        Profile profile = user.profile;
        saveProfile(profile);

        Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => baseTab()));
//        print('name----------------------${users.usersProfile.first.name}');
      });
    }else{

    }
  }


  void saveProfile (Profile profile)async{

    SharedPreferences prefs = await SharedPreferences.getInstance();

    Map <String, dynamic> map = profile.toJson();
    map.forEach((key,value){
         String newKey = 'profile_$key';
         if(value is String){
//           print('newKey------------$newKey          value------------$value');
           prefs.setString(newKey, value);
         }else {
           String valueStr = value.toString();
           prefs.setString(newKey, valueStr);
         }


      });


//    prefs.setMockInitialValues(str);


  }

  void initState() {
    super.initState();

    getAreaDNS();

  }

  @override
  void dispose() {
    // Clean up the controller when disposing of the Widget.
    _passwordController.dispose();
    _accountController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          // Here we take the value from the MyHomePage object that was created by
          // the App.build method, and use it to set our appbar title.
          title: Text(widget.title),
        ),
        body: ListView(children: <Widget>[
          Container(
            padding: EdgeInsets.only(top: 40),
            child: Image.asset(
              "lib/Login/images/login_logo.png",
              width: 90,
              height: 68,
            ),
          ),

          Container(
            padding: EdgeInsets.only(top: 10),
            child: Row(children: <Widget>[
              Expanded(
                flex: 1,
                child: Container(
                  padding: EdgeInsets.only(left: 25, right: 25),
                  child: TextField(
                    controller: _accountController,
                    decoration: InputDecoration(
                      prefixIcon: Icon(Icons.account_box),
                    ),
                    style: TextStyle(fontSize: 14.0, color: Colors.black),
                    onChanged: (text) {
                      //内容改变的回调
//                      print('account_box-----onChanged------- $text');
                    },
                    onSubmitted: (text) {
                      //内容提交(按回车)的回调
//                      print('account_box-----------submit------- $text');
                    },
                  ),
                ),
              ),
            ]),
          ),

          Container(
            padding: EdgeInsets.only(top: 10),
            child: Row(children: <Widget>[
              Expanded(
                flex: 1,
                child: Container(
                  padding: EdgeInsets.only(left: 25, right: 25),
                  child: TextField(
                    controller: _passwordController,
                    obscureText: _isObscure,
                    decoration: InputDecoration(
                      prefixIcon: Icon(Icons.https),
                      suffixIcon: StatusIconButton(onTap: (isSelected) {
                        setState(() {
                          _isObscure = !_isObscure;
                        });
                      }),
                    ),
                    style: TextStyle(fontSize: 14.0, color: Colors.black),
                    onChanged: (text) {
                      //内容改变的回调
//                      print('password----------change-------- $text');
                    },
                    onSubmitted: (text) {
                      //内容提交(按回车)的回调
//                      print('password---------submit--------- $text');
                    },
                  ),
                ),
              ),
            ]),
          ),

          Container(
            padding: EdgeInsets.only(top: 10, left: 25, right: 25),
            child: Row(children: <Widget>[
              Expanded(
                flex: 1,
                child: Container(
                  padding: EdgeInsets.only(left: 5, right: 5),
                  child: Icon(Icons.location_on),
                ),
              ),
              Expanded(
                flex: 5,
                child: Container(
                  padding: EdgeInsets.only(left: 5, right: 5),
                  child: GestureDetector(
                    child: Container(
                      color:Colors.transparent,
                      padding: EdgeInsets.only(left:5,top: 10,bottom: 10),
//                      width:100,
                      height: 50,
                      child:Text(
                        area == null ?'请选择区域' : area.areaName,
                        textAlign: TextAlign.left,
                        style: TextStyle(
                          fontSize: 16.0,
                          color: Colors.black,
                        ),
                      ),
                    ),


                    onTap: () {
                      Navigator.push(context, MaterialPageRoute(builder: (context) => areaSelectPage(title:'选择区域'))).then((dynamic result){
                        setState(() {
                          area = result;
                        });
//                        print('result-------------$result');
                      });
                    },
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: Container(
                  padding: EdgeInsets.only(left: 5, right: 5),
                  child: Icon(Icons.chevron_right),
                ),
              ),
            ]),
          ),
          Container(
            padding: EdgeInsets.only(top: 0,left: 25, right: 25),
            child: Container(
              color: Color(0xffafafae),
//              color:Colors.black,
              height: 1,
            ),
          ),
          Container(
            padding: EdgeInsets.only(top: 5,left: 25, right: 25),
            child: Row(children: <Widget>[
              Expanded(
                flex: 3,
                child: Container(
                  padding: EdgeInsets.only(top: 0),
                  child:  Container(
                    color: Colors.transparent,
                    height: 1,
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: Container(
                  color: Colors.transparent,
                  padding: EdgeInsets.only(top: 0,right: 5),
                  child: GestureDetector(

                    child: Text(
                      '忘记密码?',
                      textAlign: TextAlign.right,
                      style: TextStyle(
                        fontSize: 13.0,
                        color: Color(0xfffdc732),
                      ),
                    ),

                    onTap: () {},
                  ),
                ),
              ),

            ]),
          ),
          Container(
            padding: EdgeInsets.only(top: 10),
            child: Row(children: <Widget>[
              Expanded(
                flex: 1,
                child: Container(
                  padding: EdgeInsets.only(left: 25, right: 25),
                  child: FlatButton(
                    child: Text(
                      '登      录',
                      style: TextStyle(
                        fontSize: 16.0,
                        color: Colors.white,
                      ),
                    ),
                    color: Colors.blue,
                    textColor: Colors.white,
                    onPressed: () {


                      checkResult();
//                       Navigator.push(context, MaterialPageRoute(builder: (context) => MyHomePage()));
//                        Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => MyHomePage()));
                    },
                  ),
                ),
              ),
            ]),
          ),

        ])
      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class StatusIconButton extends StatefulWidget {
//  String  NormalImageName;
//  String  SelectedImageName;

  @required
  ValueChanged<bool> onTap;
  StatusIconButton({this.onTap});

  @override
  _StatusIconButtonState createState() => _StatusIconButtonState();
}

class _StatusIconButtonState extends State<StatusIconButton> {
  bool _isSelected = false;
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(top: 10),
      child: IconButton(
        icon: _isSelected
            ? new Icon(Icons.visibility_off)
            : new Icon(Icons.visibility),
        onPressed: () {
          _isSelected = !_isSelected;
          widget.onTap(_isSelected);
        },
      ),
    );
  }
}





